package cn.ajb.filemanager.controller;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ajb.filemanager.entity.User;
import cn.ajb.filemanager.service.UserService;
import cn.ajb.filemanager.util.Contant;
import cn.ajb.filemanager.util.md5.Md5Pwd;

/**
 * 用户控制类
 * @author zoujing
 *
 */
@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private Md5Pwd md5Pwd;
	@Autowired
	private Contant contant;
	//密码的修改
	@RequestMapping(value="/updateUser")
	public void updateUser(Integer type,String oldpassword,String newpassword,HttpServletRequest request,HttpServletResponse response){
		try {
			User user=new User();
			//将新密码进行MD5加密、
			newpassword=md5Pwd.encode(newpassword);
			//先判断修改的是什么
			if(type==0){
					user=(User) request.getSession().getAttribute(contant.getUser());
					//将oldPassword也进行加密然后比较
					
					if(!user.getPassword().equals(md5Pwd.encode(oldpassword))){
						//2、输出更新结果
						
						response.setContentType("text/html");
						ServletOutputStream outputStream = response.getOutputStream();
						outputStream.write("error".getBytes("utf-8"));
						outputStream.close();
					}else{
						//修改管理员
						user.setPassword(newpassword);
						userService.updateUser(user);
						request.getSession().setAttribute(contant.getUser(), user);
						
						
						response.setContentType("text/html");
						ServletOutputStream outputStream = response.getOutputStream();
						outputStream.write("success".getBytes("utf-8"));
						outputStream.close();
					}
				}else{
					//技术人员
					user = userService.findById("2");
					user.setPassword(newpassword);
					userService.updateUser(user);
					response.setContentType("text/html");
					ServletOutputStream outputStream = response.getOutputStream();
					outputStream.write("success".getBytes("utf-8"));
					outputStream.close();
				}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}
